﻿using iWareModels;
using XiangziProjectTemplete.Core.Api.Common;
using XiangziProjectTemplete.Core.Common.Helper;
using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.IRepository.UnitOfWork;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.CommonModel;
using XiangziProjectTemplete.Core.Model.Enums.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model.Enums.XiangziProjectTemplete.LESPublicCommon;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.PostParamModels.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model.ViewModels;
using XiangziProjectTemplete.Core.Model.ViewModels.BasicData;
using XiangziProjectTemplete.Core.Model.ViewModels.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Utility;
using LesCCService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace XiangziProjectTemplete.Core.Api.Controllers
{
    /// <summary> 
    /// 公共控制器 
    /// </summary> 
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CommonController : ControllerBase
    {
        private readonly ILes_AgvTaskServices _agvTaskServices;
        private readonly IV_StationServices _V_StationServices;
        private readonly IV_CodeItemsServices _v_CodeItemsServices;
        private readonly ILogger<CommonController> _logger;
        private readonly IUser _user;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IBase_CodeItemsServices _base_CodeItemsServices;
        private readonly IBase_StationServices _base_StationServices;
        private readonly ILes_AgvWarningServices _les_AgvWarningServices;
        private readonly IV_LES_BufferStockCollectByStationServices _v_LES_BufferStockCollectByStationServices;
        private readonly ILes_AgvTaskServices _les_AgvTaskServices;

        public CommonController(
            ILes_AgvTaskServices les_AgvTaskServices,
            IV_LES_BufferStockCollectByStationServices v_LES_BufferStockCollectByStationServices,
            ILes_AgvWarningServices les_AgvWarningServices,
            IBase_StationServices base_StationServices,
            IBase_CodeItemsServices base_CodeItemsServices,
            IV_CodeItemsServices v_CodeItemsServices, IV_StationServices V_StationServices,
             ILogger<CommonController> logger, IUser user, IUnitOfWork unitOfWork, ILes_AgvTaskServices agvTaskServices)
        {
            this._les_AgvTaskServices = les_AgvTaskServices;
            this._v_LES_BufferStockCollectByStationServices = v_LES_BufferStockCollectByStationServices;
            this._les_AgvWarningServices = les_AgvWarningServices;
            this._base_StationServices = base_StationServices;
            _v_CodeItemsServices = v_CodeItemsServices;
            _V_StationServices = V_StationServices;
            _logger = logger;
            _unitOfWork = unitOfWork;
            _user = user;
            _agvTaskServices = agvTaskServices;
            this._base_CodeItemsServices = base_CodeItemsServices;
        }

        /// <summary> 
        /// 获取一类枚举
        /// </summary> 
        /// <param name="category">分类</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        public MessageModel<List<SelectViewModel>> GetEnumberList(string category)
        {
            List<EnumberEntity> _list = null;
            switch (category)
            {
                case "TaskStatusEnum":
                    _list = EnumberHelper.EnumToList<TaskStatusEnum>();
                    break;
                case "AGVTaskType":
                    _list = EnumberHelper.EnumToList<AGVTaskType>();
                    break;
                case "PrepareMatStateEnum":
                    _list = EnumberHelper.EnumToList<PrepareMatStateEnum>();
                    break;
                case "LesTaskStatusEnum":
                    _list = EnumberHelper.EnumToList<LesTaskStatusEnum>();
                    break;
                case "LesTaskModeEnum":
                    _list = EnumberHelper.EnumToList<LesTaskModeEnum>();
                    break;
                case "InOutStockTypeEnum":
                    _list = EnumberHelper.EnumToList<InOutStockTypeEnum>();
                    break;
                case "AgvWarningStatusEnum":
                    _list = EnumberHelper.EnumToList<AgvWarningStatusEnum>();
                    break;
                case "DataSourceEnum":
                    _list = EnumberHelper.EnumToList<DataSourceEnum>();
                    break;
                default:
                    break;
            }
            List<SelectViewModel> reusltDataList = new List<SelectViewModel>();
            foreach (var item in _list)
            {
                reusltDataList.Add(new SelectViewModel()
                {
                    value = item.EnumValue,//码表的ID值
                    label = item.EnumName
                });
            }
            return new MessageModel<List<SelectViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = reusltDataList
            };
        }

        /// <summary>
        /// 通过代码集获取代码项集合
        /// </summary>
        /// <param name="setCode">代码集编码</param>
        /// <returns>代码项集合</returns>
        [HttpGet]
        public async Task<MessageModel<List<SelectViewModel_Extensions>>> GetCodeItemsBySetCode(string setCode)
        {
            List<SelectViewModel_Extensions> reusltDataList = new List<SelectViewModel_Extensions>();
            var queryData = await _v_CodeItemsServices.Query(x => x.setCodeCode == setCode);
            foreach (var item in queryData)
            {
                reusltDataList.Add(new SelectViewModel_Extensions()
                {
                    value = item.Id.ToString(),//码表的ID值
                    label = item.name
                });
            }
            return new MessageModel<List<SelectViewModel_Extensions>>()
            {
                msg = "获取成功",
                success = true,
                response = reusltDataList
            };
        }

        /// <summary> 
        /// 获取一类站点管理 
        /// </summary> 
        /// <param name="category">分类</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        public async Task<MessageModel<List<V_Station>>> GetByCategory(string category)
        {
            var _list = await _V_StationServices.GetStationByCategory(category);
            return new MessageModel<List<V_Station>>()
            {
                msg = "获取成功",
                success = true,
                response = _list
            };
        }




        /// <summary>
        /// 获取大类物料，按照分级结构
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<CascaderSelectViewModel>>> GetBigMaterialsForCascader()
        {
            List<CascaderSelectViewModel> csvList = new List<CascaderSelectViewModel>();
            //首先获取工序
            var procedureResult = await _base_CodeItemsServices.GetCodeItemsBySetCode("LES_GX");//工序的码表集编码
            if (procedureResult.success == false)
            {
                return MessageModel<List<CascaderSelectViewModel>>.Fail(procedureResult.msg);
            }
            List<Base_CodeItems> procedureList = procedureResult.response;
            if (procedureList != null && procedureList.Count > 0)
            {
                foreach (var procedure in procedureList)
                {
                    var procedure_CascaderSelectViewModel = new CascaderSelectViewModel()
                    {
                        label = procedure.name,
                        value = procedure.Id,
                        name = procedure.code
                    };
                    //其次获取工序下的大类物料集合
                    var materialsResult = await _base_CodeItemsServices.GetCodeItemsBySetCode(procedure.code);
                    if (materialsResult.success == false)
                    {
                        return MessageModel<List<CascaderSelectViewModel>>.Fail(materialsResult.msg);
                    }
                    procedure_CascaderSelectViewModel.children = new List<CascaderSelectViewModel>();
                    procedure_CascaderSelectViewModel.children = LesApiCommon.ConvertToCascaderSelectViewModel(materialsResult.response);

                    csvList.Add(procedure_CascaderSelectViewModel);
                }
                return MessageModel<List<CascaderSelectViewModel>>.Success("成功", csvList);
            }
            else
            {
                return MessageModel<List<CascaderSelectViewModel>>.Fail("没有物料数据");
            }
        }



        /// <summary>
        /// 获取站点，按照 工序的 分级结构
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<CascaderSelectViewModel>>> GetStaionsByProcedureForCascader()
        {
            List<CascaderSelectViewModel> csvList = new List<CascaderSelectViewModel>();
            //首先获取工序
            var procedureResult = await _base_CodeItemsServices.GetCodeItemsBySetCode("LES_GX");//工序的码表集编码
            if (procedureResult.success == false)
            {
                return MessageModel<List<CascaderSelectViewModel>>.Fail(procedureResult.msg);
            }
            List<Base_CodeItems> procedureList = procedureResult.response;
            if (procedureList != null && procedureList.Count > 0)
            {
                foreach (var procedure in procedureList)
                {
                    var procedure_CascaderSelectViewModel = new CascaderSelectViewModel()
                    {
                        label = procedure.name,
                        value = procedure.Id,
                        name = procedure.code
                    };
                    //其次获取工序下的站点集合
                    var stationResult = await _base_StationServices.GetStationsByProcedure(procedure.Id);
                    if (stationResult.success == false)
                    {
                        return MessageModel<List<CascaderSelectViewModel>>.Fail(stationResult.msg);
                    }
                    procedure_CascaderSelectViewModel.children = new List<CascaderSelectViewModel>();
                    procedure_CascaderSelectViewModel.children = LesApiCommon.ConvertToCascaderSelectViewModel(stationResult.response);

                    csvList.Add(procedure_CascaderSelectViewModel);
                }
                return MessageModel<List<CascaderSelectViewModel>>.Success("成功", csvList);
            }
            else
            {
                return MessageModel<List<CascaderSelectViewModel>>.Fail("没有站点数据");
            }
        }



        /// <summary>
        /// 取消AGV任务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<string>> CancelAgvTask([FromBody] CancelAgvTaskPostParam request)
        {
            var data = new MessageModel<string>();

            try
            {
                #region 验证
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<CancelAgvTaskPostParam, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>() {
                   new ValidateModel(){ ChinaName="业务表", DataType=typeof(string), DataValue=request.BussinessTableName },
                   new ValidateModel(){ ChinaName="XiangziProjectTemplete任务号", DataType=typeof(string), DataValue=request.LesTaskId },
                   new ValidateModel(){ ChinaName="取消说明", DataType=typeof(string), DataValue=request.Remark },
                };
                retBody = ValidateDataHelper.CommonValidate<CancelAgvTaskPostParam, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }

                #endregion

                request.UserName = _user.Name;

                string requestStr = JsonConvert.SerializeObject(request);
                using (LesCCService.LesCCServiceClient client = new LesCCService.LesCCServiceClient())
                {
                    SdaResEntity sdaRes = await client.CancelAgvTaskAsync(requestStr);
                    if (sdaRes.resultk__BackingField)
                    {
                        return MessageModel<string>.Success("成功");
                    }
                    else
                    {
                        return MessageModel<string>.Fail("验证失败:" + sdaRes.resMsgk__BackingField,
                            sdaRes.resDatak__BackingField == null ? "" : sdaRes.resDatak__BackingField.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "取消AGV任务 出现异常:" + ex.Message);
                return MessageModel<string>.Fail("取消AGV任务 出现异常:" + ex.Message);
            }
        }


        /// <summary>
        /// 强制完成AGV任务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<string>> CoerceFinishAgvTask([FromBody] CoerceFinishAgvTaskPostParam request)
        {
            var data = new MessageModel<string>();

            try
            {
                #region 验证
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<CoerceFinishAgvTaskPostParam, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>() {
                   new ValidateModel(){ ChinaName="业务表", DataType=typeof(string), DataValue=request.BussinessTableName },
                   new ValidateModel(){ ChinaName="XiangziProjectTemplete任务号", DataType=typeof(string), DataValue=request.LesTaskId },
                   new ValidateModel(){ ChinaName="取消说明", DataType=typeof(string), DataValue=request.Remark },
                };
                retBody = ValidateDataHelper.CommonValidate<CoerceFinishAgvTaskPostParam, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }

                #endregion

                request.UserName = _user.Name;

                string requestStr = JsonConvert.SerializeObject(request);
                using (LesCCService.LesCCServiceClient client = new LesCCService.LesCCServiceClient())
                {
                    SdaResEntity sdaRes = await client.CoerceFinishAgvTaskAsync(requestStr);
                    if (sdaRes.resultk__BackingField)
                    {
                        return MessageModel<string>.Success("成功");
                    }
                    else
                    {
                        return MessageModel<string>.Fail("验证失败:" + sdaRes.resMsgk__BackingField,
                            sdaRes.resDatak__BackingField == null ? "" : sdaRes.resDatak__BackingField.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "强制完成AGV任务 出现异常:" + ex.Message);
                return MessageModel<string>.Fail("强制完成AGV任务 出现异常:" + ex.Message);
            }
        }


        /// <summary>
        /// 清理库存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<string>> ClearStoreByStation([FromBody] ClearStoreByStationPostParam request)
        {
            var data = new MessageModel<string>();

            try
            {
                #region 验证
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<ClearStoreByStationPostParam, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>() {
                   new ValidateModel(){ ChinaName="站点", DataType=typeof(int), DataValue=request.StationId },
                   new ValidateModel(){ ChinaName="说明", DataType=typeof(string), DataValue=request.Remark },
                };
                retBody = ValidateDataHelper.CommonValidate<ClearStoreByStationPostParam, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }

                #endregion

                request.UserName = _user.Name;

                string requestStr = JsonConvert.SerializeObject(request);
                using (LesCCService.LesCCServiceClient client = new LesCCService.LesCCServiceClient())
                {
                    SdaResEntity sdaRes = await client.ClearStoreByStationAsync(requestStr);
                    if (sdaRes.resultk__BackingField)
                    {
                        return MessageModel<string>.Success("成功");
                    }
                    else
                    {
                        return MessageModel<string>.Fail("验证失败:" + sdaRes.resMsgk__BackingField,
                            sdaRes.resDatak__BackingField == null ? "" : sdaRes.resDatak__BackingField.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理库存 出现异常:" + ex.Message);
                return MessageModel<string>.Fail("清理库存 出现异常:" + ex.Message);
            }
        }


        /// <summary>
        /// 增加库存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<string>> AddStoreByStation([FromBody] AddStoreByStationPostParam request)
        {
            var data = new MessageModel<string>();

            try
            {
                #region 验证
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<AddStoreByStationPostParam, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>() {
                   new ValidateModel(){ ChinaName="站点", DataType=typeof(int), DataValue=request.StationId },
                   new ValidateModel(){ ChinaName="物料码表中的编号", DataType=typeof(string), DataValue=request.CodeItemsByCode },
                   new ValidateModel(){ ChinaName="说明", DataType=typeof(string), DataValue=request.Remark },
                };
                retBody = ValidateDataHelper.CommonValidate<AddStoreByStationPostParam, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }

                #endregion

                request.UserName = _user.Name;

                string requestStr = JsonConvert.SerializeObject(request);
                using (LesCCService.LesCCServiceClient client = new LesCCService.LesCCServiceClient())
                {
                    SdaResEntity sdaRes = await client.AddStoreByStationAsync(requestStr);
                    if (sdaRes.resultk__BackingField)
                    {
                        return MessageModel<string>.Success("成功");
                    }
                    else
                    {
                        return MessageModel<string>.Fail("验证失败:" + sdaRes.resMsgk__BackingField,
                            sdaRes.resDatak__BackingField == null ? "" : sdaRes.resDatak__BackingField.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "增加库存 出现异常:" + ex.Message);
                return MessageModel<string>.Fail("增加库存 出现异常:" + ex.Message);
            }
        }

        #region 首页内容

        /// <summary>
        /// 获取首页内容
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<WelcomeDataViewModel>> GetWelcomeData()
        {
            var data = new MessageModel<WelcomeDataViewModel>();

            try
            {
                WelcomeDataViewModel welcomeDataViewModel = new WelcomeDataViewModel();
                var noStartList = await _agvTaskServices.Query(x => x.TaskStatus == Convert.ToInt32(TaskStatusEnum.未开始));
                var issueList = await _agvTaskServices.Query(x => x.TaskStatus == Convert.ToInt32(TaskStatusEnum.已下发));

                welcomeDataViewModel.AllNoStartTaskCount = noStartList.Count;
                welcomeDataViewModel.AllIssueTaskCount = issueList.Count;
                welcomeDataViewModel.AllRuningTaskCount = noStartList.Count + issueList.Count;

                var BEING_PROCESSED = await _agvTaskServices.Query(x => (x.TaskStatus == Convert.ToInt32(TaskStatusEnum.已下发) || x.TaskStatus == Convert.ToInt32(TaskStatusEnum.未开始)) && x.AgvState == Convert.ToString(AgvTaskStateEnum.BEING_PROCESSED));
                welcomeDataViewModel.BEING_PROCESSED_Count = BEING_PROCESSED.Count;

                var DISPATCHABLE = await _agvTaskServices.Query(x => (x.TaskStatus == Convert.ToInt32(TaskStatusEnum.已下发) || x.TaskStatus == Convert.ToInt32(TaskStatusEnum.未开始)) && x.AgvState == Convert.ToString(AgvTaskStateEnum.DISPATCHABLE));
                welcomeDataViewModel.AllWaitForDistributionTaskCount = DISPATCHABLE.Count;

                //获取报警记录
                var warningList = await _les_AgvWarningServices.Query(x => x.Status == 0);
                welcomeDataViewModel.AgvWarningList = new List<AgvWarningViewModel>();
                welcomeDataViewModel.AgvWarnCount = warningList.Count;
                if (warningList.Count == 0)
                {
                    AgvWarningViewModel les_AgvWarning = new AgvWarningViewModel()
                    {
                        AgvName = "",
                        AgvNameDesc = "无",
                        Str_WarningTime = ""
                    };
                    welcomeDataViewModel.AgvWarningList.Add(les_AgvWarning);
                }
                else
                {
                    AgvWarningViewModel les_AgvWarning = null;
                    foreach (var item in warningList)
                    {
                        les_AgvWarning = new AgvWarningViewModel();
                        les_AgvWarning = ClassHelper.RotationMapping<AgvWarningViewModel, Les_AgvWarning>(item);
                        les_AgvWarning.Str_WarningTime = DateTimeHelper.ConvertToString(item.WarningTime);
                        welcomeDataViewModel.AgvWarningList.Add(les_AgvWarning);
                    }
                }

                data.response = welcomeDataViewModel;

                return data;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取首页内容 出现异常:" + ex.Message);
                return MessageModel<WelcomeDataViewModel>.Fail("获取首页内容 出现异常:" + ex.Message);
            }
        }

        /// <summary>
        /// 获取首页内容(库存饼图)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<List<PieViewModel>>> GetWelcomeDataForPie()
        {
            var data = new MessageModel<List<PieViewModel>>();
            List<PieViewModel> arrList = new List<PieViewModel>();
            try
            {

                PieViewModel welcomeDataViewModel = new PieViewModel();
                var allList = await _v_LES_BufferStockCollectByStationServices.Query(x => x.StoreAreaCode == Convert.ToString(StoreAreaEnum.StoreBuffer));

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "物料空库位";
                welcomeDataViewModel.value = allList.Where(x => (x.IsFull == null || x.IsFull == 0) && x.PlaceTypeCode == Convert.ToInt32(StationPlaceTypeEnum.货物工位).ToString()).Count().ToString();
                arrList.Add(welcomeDataViewModel);

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "空托盘或余料空库位";
                welcomeDataViewModel.value = allList.Where(x => (x.IsFull == null || x.IsFull == 0) && x.PlaceTypeCode == Convert.ToInt32(StationPlaceTypeEnum.余料工位).ToString()).Count().ToString();
                arrList.Add(welcomeDataViewModel);

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "物料托数";
                welcomeDataViewModel.value = allList.Where(x => x.IsFull == 1 && x.PlaceTypeCode == Convert.ToInt32(StationPlaceTypeEnum.货物工位).ToString()).Count().ToString();
                arrList.Add(welcomeDataViewModel);

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "空托盘或余料托数";
                welcomeDataViewModel.value = allList.Where(x => x.IsFull == 1 && x.PlaceTypeCode == Convert.ToInt32(StationPlaceTypeEnum.余料工位).ToString()).Count().ToString();
                arrList.Add(welcomeDataViewModel);


                data.response = arrList;

                return data;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取 库存饼图 出现异常:" + ex.Message);
                return MessageModel<List<PieViewModel>>.Fail("获取 库存饼图 出现异常:" + ex.Message);
            }
        }


        /// <summary>
        /// 饼图-AGV利用率
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<List<PieViewModel>>> GetAgvForUseRatioPie(DateTime startTime, DateTime endTime)
        {
            var data = new MessageModel<List<PieViewModel>>();
            List<PieViewModel> arrList = new List<PieViewModel>();
            try
            {
                DateTime newStartTime = DateTimeHelper.GetDayStart(startTime);
                DateTime newEndTime = DateTimeHelper.GetDayEnd(endTime);
                PieViewModel welcomeDataViewModel = new PieViewModel();

                //这段时间的AGV任务清单
                var allTaskList = await _les_AgvTaskServices.Query(x => x.CreateTime >= newStartTime && x.CreateTime <= newEndTime && !string.IsNullOrEmpty(x.ProcessingVehicle));

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "1号车";
                welcomeDataViewModel.value = allTaskList.Where(x => x.ProcessingVehicle == "Vehicle-0001").Count().ToString();
                arrList.Add(welcomeDataViewModel);

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "2号车";
                welcomeDataViewModel.value = allTaskList.Where(x => x.ProcessingVehicle == "Vehicle-0002").Count().ToString();
                arrList.Add(welcomeDataViewModel);

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "3号车";
                welcomeDataViewModel.value = allTaskList.Where(x => x.ProcessingVehicle == "Vehicle-0003").Count().ToString();
                arrList.Add(welcomeDataViewModel);

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "4号车";
                welcomeDataViewModel.value = allTaskList.Where(x => x.ProcessingVehicle == "Vehicle-0004").Count().ToString();
                arrList.Add(welcomeDataViewModel);

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "5号车";
                welcomeDataViewModel.value = allTaskList.Where(x => x.ProcessingVehicle == "Vehicle-0005").Count().ToString();
                arrList.Add(welcomeDataViewModel);

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "6号车";
                welcomeDataViewModel.value = allTaskList.Where(x => x.ProcessingVehicle == "Vehicle-0006").Count().ToString();
                arrList.Add(welcomeDataViewModel);

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "7号车";
                welcomeDataViewModel.value = allTaskList.Where(x => x.ProcessingVehicle == "Vehicle-0007").Count().ToString();
                arrList.Add(welcomeDataViewModel);

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "8号车";
                welcomeDataViewModel.value = allTaskList.Where(x => x.ProcessingVehicle == "Vehicle-0008").Count().ToString();
                arrList.Add(welcomeDataViewModel);

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "9号车";
                welcomeDataViewModel.value = allTaskList.Where(x => x.ProcessingVehicle == "Vehicle-0009").Count().ToString();
                arrList.Add(welcomeDataViewModel);

                welcomeDataViewModel = new PieViewModel();
                welcomeDataViewModel.key = "10号车";
                welcomeDataViewModel.value = allTaskList.Where(x => x.ProcessingVehicle == "Vehicle-0010").Count().ToString();
                arrList.Add(welcomeDataViewModel);



                data.response = arrList;

                return data;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取 饼图-AGV利用率 出现异常:" + ex.Message);
                return MessageModel<List<PieViewModel>>.Fail("获取 饼图-AGV利用率 出现异常:" + ex.Message);
            }
        }


        /// <summary>
        /// 获取XX天的AGV任务曲线图（首页使用）
        /// </summary>
        /// <param name="day">指定天数</param>
        /// <param name="flag">1：任务完成的  2：新建任务的</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<WelcomeAccessApiDateView_AGV>> ProductYieldByTimeRange(int day, int flag)
        {
            try
            {

                #region 获取总产量
                var queryTime = DateTime.Now.AddDays(-day);
                List<WelcomeApiDate> welcomeApiDateList = new List<WelcomeApiDate>();
                List<Les_AgvTask> pieces = new List<Les_AgvTask>();
                if (flag == 1)
                {
                    pieces = await _agvTaskServices.Query(d => d.TaskStatus == Convert.ToInt32(TaskStatusEnum.已完成) && d.TaskFinishTime >= queryTime);
                    welcomeApiDateList = (from n in pieces
                                          group n by new { n.TaskFinishTime.ObjToDate().Date } into g
                                          select new WelcomeApiDate
                                          {
                                              日期 = g.Key?.Date.ToString("yyyy-MM-dd"),
                                              总量 = g.Count(),
                                              车辆1 = g.Where(x => x.ProcessingVehicle == "Vehicle-0001").Count(),
                                              车辆2 = g.Where(x => x.ProcessingVehicle == "Vehicle-0002").Count(),
                                              车辆3 = g.Where(x => x.ProcessingVehicle == "Vehicle-0003").Count(),
                                              车辆4 = g.Where(x => x.ProcessingVehicle == "Vehicle-0004").Count(),
                                              车辆5 = g.Where(x => x.ProcessingVehicle == "Vehicle-0005").Count(),
                                              车辆6 = g.Where(x => x.ProcessingVehicle == "Vehicle-0006").Count(),
                                              车辆7 = g.Where(x => x.ProcessingVehicle == "Vehicle-0007").Count(),
                                              车辆8 = g.Where(x => x.ProcessingVehicle == "Vehicle-0008").Count(),
                                              车辆9 = g.Where(x => x.ProcessingVehicle == "Vehicle-0009").Count(),
                                              车辆10 = g.Where(x => x.ProcessingVehicle == "Vehicle-0010").Count(),
                                              未分配 = g.Where(x => string.IsNullOrEmpty(x.ProcessingVehicle)).Count()

                                          }).ToList();
                }
                else if (flag == 2)
                {
                    pieces = await _agvTaskServices.Query(d => d.CreateTime >= queryTime);
                    welcomeApiDateList = (from n in pieces
                                          group n by new { n.CreateTime.ObjToDate().Date } into g
                                          select new WelcomeApiDate
                                          {
                                              日期 = g.Key?.Date.ToString("yyyy-MM-dd"),
                                              总量 = g.Count(),
                                              车辆1 = g.Where(x => x.ProcessingVehicle == "Vehicle-0001").Count(),
                                              车辆2 = g.Where(x => x.ProcessingVehicle == "Vehicle-0002").Count(),
                                              车辆3 = g.Where(x => x.ProcessingVehicle == "Vehicle-0003").Count(),
                                              车辆4 = g.Where(x => x.ProcessingVehicle == "Vehicle-0004").Count(),
                                              车辆5 = g.Where(x => x.ProcessingVehicle == "Vehicle-0005").Count(),
                                              车辆6 = g.Where(x => x.ProcessingVehicle == "Vehicle-0006").Count(),
                                              车辆7 = g.Where(x => x.ProcessingVehicle == "Vehicle-0007").Count(),
                                              车辆8 = g.Where(x => x.ProcessingVehicle == "Vehicle-0008").Count(),
                                              车辆9 = g.Where(x => x.ProcessingVehicle == "Vehicle-0009").Count(),
                                              车辆10 = g.Where(x => x.ProcessingVehicle == "Vehicle-0010").Count(),
                                              未分配 = g.Where(x => string.IsNullOrEmpty(x.ProcessingVehicle)).Count()
                                          }).ToList();
                }


                welcomeApiDateList = welcomeApiDateList.OrderByDescending(d => d.日期).Take(day).ToList();


                if (welcomeApiDateList.Count == 0)
                {
                    welcomeApiDateList.Add(new WelcomeApiDate()
                    {
                        日期 = "没数据",
                        总量 = 0
                    });
                }

                #endregion

                return new MessageModel<WelcomeAccessApiDateView_AGV>()
                {
                    msg = "获取成功",
                    success = true,
                    response = new WelcomeAccessApiDateView_AGV
                    {
                        columns = new string[] { "日期", "总量", "车辆1", "车辆2", "车辆3", "车辆4", "车辆5", "车辆6", "车辆7", "车辆8", "车辆9", "车辆10" },
                        rows = welcomeApiDateList.OrderBy(d => d.日期).ToList(),
                    }
                };
            }
            catch (Exception ex)
            {
                _logger.LogError("获取XX天的AGV任务 出现异常", ex);
                return new MessageModel<WelcomeAccessApiDateView_AGV>()
                {
                    msg = "异常:" + ex.Message,
                    success = false,
                    response = null
                };
            }

        }

        #endregion

    }
}
